package com.scs.application.modules.sys.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.consts.GlobalConsts;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.query.QueryContextHolder;
import com.scs.application.modules.base.annotation.MarkParameter;
import com.scs.application.modules.sys.adapter.DictAdapter;
import com.scs.application.modules.sys.dto.DictDTO;
import com.scs.application.modules.sys.entity.DictData;
import com.scs.application.modules.sys.entity.DictType;
import com.scs.application.modules.sys.model.PageResult;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.sys.properties.SystemProperties;
import com.scs.application.modules.sys.request.DictRequest;
import com.scs.application.modules.sys.service.DictTypeService;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/sys/dict_type")
public class DictTypeController {

    @Autowired
    private DictAdapter dictAdapter;

    @Autowired
    private SystemProperties systemProperties;

    /**
     * 获取数据列表
     */
    @GetMapping("/page")
    public PageResult page(HttpServletRequest request) {
        QueryContext queryContext = QueryContextHolder.currentContext();
        IPage pageResult = dictAdapter.getDictTypeService().page(queryContext);
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }

    @GetMapping("/list")
    public RestResult<List> list() {
        QueryContext queryContext = QueryContextHolder.currentContext();
        List result = dictAdapter.getDictTypeService().list(queryContext);
        return RestResult.ok("查询成功", result);
    }

    /**
     * 获取所有数据
     *
     * @param onlyBusFields 仅查询业务字段
     * @return
     */
    @GetMapping("/all")
    public RestResult findAll(@RequestParam(required = false) boolean onlyBusFields) {
        List<DictType> models = dictAdapter.getDictTypeService().list();
        return RestResult.ok("查询成功", models);
    }

    /**
     * 获取字典比对
     *
     * @param code 获取字典比对
     * @return
     */
    @GetMapping("/diff")
    public RestResult getTwoDictTypes(@RequestParam String code) {
        DictTypeService fileDictTypeService = dictAdapter.getDictTypeService(false);
        if (fileDictTypeService.getClass().getName().equals(dictAdapter.getDictTypeService().getClass().getName())) {
            throw new BusinessException("产品分支不支持该功能");
        }

        HashMap<String, Object> result = new HashMap<>();
        DictDTO fileDictDTO = fileDictTypeService.getDictDTOByCode(code);
        result.put("productDictDTO", JSON.toJSONString(fileDictDTO));

        DictDTO dictDTO = dictAdapter.getDictTypeService().getDictDTOByCode(code);
        result.put("projectDictDTO", JSON.toJSONString(dictDTO));
        return RestResult.ok("获取数据成功", result);
    }

    /**
     * 同步产品视图
     *
     * @param dictRequest
     * @return
     */
    @PostMapping(value = "/sync")
    public RestResult syncDict(@Valid @RequestBody DictRequest dictRequest) {
        DictTypeService dictTypeService = dictAdapter.getDictTypeService(!systemProperties.getFlagProject());
        DictDTO dictDTO = dictTypeService.getDictDTOByCode(dictRequest.getCode());

        if (dictDTO == null) {
            return RestResult.error("同步数据失败,该字典可能不存在");
        }
        DictType dictType = new DictType();
        BeanUtils.copyProperties(dictDTO, dictType);
        dictAdapter.getDictTypeService().saveOrUpdate(dictType);
        dictAdapter.getDictDataService().remove(Wrappers.<DictData>query().eq("dict_type_id", dictType.getId()));
        if (dictDTO.getDictDataDTOS() != null && dictDTO.getDictDataDTOS().size() > 0) {
            dictDTO.getDictDataDTOS().forEach(dictDataDTO -> {
                DictData dictData = new DictData();
                BeanUtils.copyProperties(dictDataDTO, dictData);
                dictAdapter.getDictDataService().saveOrUpdate(dictData);
            });
        }
        return RestResult.ok("同步数据成功", dictDTO);
    }


    /**
     * 根据ID查找数据
     */
    @GetMapping("/find")
    public RestResult find(@RequestParam("id") Serializable id) {
        DictType entity = dictAdapter.getDictTypeService().getById(id);
        if (entity == null) {
            return RestResult.error("数据查询失败<br>可能所操作数据已被删除，请刷新后重新尝试操作");
        }
        return RestResult.ok("获取数据成功", entity);
    }


    /**
     * 添加/更新数据
     */
    @PostMapping("/save")
    @MarkParameter(type = GlobalConsts.MarkParameterTYpe.DICT_TYPE,msg = "数据字典类型变化")
    public RestResult saveItem(@Valid @RequestBody DictType entity) {
        boolean isOk = dictAdapter.getDictTypeService().saveOrUpdate(entity);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        return RestResult.ok("数据保存成功", entity);
    }

    /**
     * 添加/更新数据
     */
    @PostMapping("/saveDTO")
    @MarkParameter(type = GlobalConsts.MarkParameterTYpe.DICT_TYPE,msg = "数据字典类型变化")
    public RestResult saveDTO(@Valid @RequestBody DictDTO entity) {
        DictType dictType = new DictType();
        BeanUtils.copyProperties(entity, dictType);
        boolean isOk = dictAdapter.getDictTypeService().saveOrUpdate(dictType);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        if (entity.getDictDataDTOS() != null && !entity.getDictDataDTOS().isEmpty()) {
            List<DictData> dictDataList = Lists.newArrayList();
            for (DictDTO.DictDataDTO dictDataDTO : entity.getDictDataDTOS()) {
                DictData dictData = new DictData();
                BeanUtils.copyProperties(dictDataDTO, dictData);
                dictDataList.add(dictData);
            }
            dictAdapter.getDictDataService().saveOrUpdateBatch(dictDataList);
        }
        return RestResult.ok("数据保存成功", entity);
    }

    /**
     * 删除数据
     */
    @DeleteMapping("/delete")
    @MarkParameter(type = GlobalConsts.MarkParameterTYpe.DICT_TYPE,msg = "数据字典类型变化")
    public RestResult deleteItems(@RequestBody Map<String, Object> para) {
        List<Serializable> ids = (List<Serializable>) para.get("ids");
        Boolean isOk = dictAdapter.getDictTypeService().removeCascadeByIds(ids);
        if (!isOk) {
            return RestResult.error("数据删除失败<br>可能所操作数据已被删除，请刷新页面重新尝试操作");
        }
        return RestResult.ok("数据删除成功");
    }

}
